package com.nyf.web;


import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.nyf.dao.UserDao;
import com.nyf.entity.User;

public class LoginServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("go to login.jsp......................");
		request.getRequestDispatcher("/WEB-INF/views/index.jsp").forward(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String name = request.getParameter("username");
		System.out.println("username:" + name);
		
		String password = request.getParameter("password");
		UserDao dao = new UserDao();
		
		User user = dao.findByName(name);
		
		if(user != null && user.getPassword().equals(password)) {
			HttpSession session = request.getSession();
			session.setAttribute("user", user);
			
			String where = (String) session.getAttribute("where");
			if(where != null) {
				session.removeAttribute("where");
				response.sendRedirect(where);
			} else {
				response.sendRedirect("main.jspx");
			}
		} else {
			response.sendRedirect("login.jspx?code=10001");
		}
		
		
	}
	
}
